package cn.itcast.demo.task;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class ClearOrderTask2 {

    @Autowired
    private RedissonClient redissonClient;

    @Scheduled(cron = "0/10 * * ? * *")
    public synchronized void clearOrderTask() throws InterruptedException {
        // 获取锁对象
        RLock lock = redissonClient.getLock("lock");

        RLock redLock = redissonClient.getRedLock(lock);
        redLock.tryLock();
        // 尝试加锁，不带阻塞功能的可重入锁
        boolean isLock = lock.tryLock(0, 1, TimeUnit.MINUTES);
        // 判断是否成功
        if(!isLock){
            // 获取锁失败，结束任务
            log.error("获取锁失败，任务终止！");
            return;
        }
        try {
            log.info("获取锁成功，开始执行任务");
            // 执行任务
            clearOrder();
        }finally {
            // 释放锁
            log.warn("任务结束，释放锁");
            lock.unlock();
        }
    }

    private void clearOrder() throws InterruptedException {
        log.info("开始清理未支付订单!");
        Thread.sleep(500);
        log.info("恢复数据库库存！");
    }
}